package com.xuwangcheng.html2word.handler;

import com.deepoove.poi.data.style.Style;
import com.xuwangcheng.html2word.HandlerParams;
import org.apache.poi.xwpf.usermodel.XWPFRelation;
import org.jsoup.nodes.Element;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.math.BigInteger;

/**
 * A标签转换
 * @author xuwangcheng
 * @version 1.0.0
 * @description
 * @date 2023/9/18 11:05
 */
public class ATagHandler extends BaseHtmlTagHandler  {

    @Override
    public String getMatchTagName() {
        return "a";
    }

    @Override
    public void handleHtmlElement(HandlerParams params, Style style) {
        Element element = (Element) params.getCurrentNode();
        String text = element.wholeText();
        String src = element.attr("href");

        // Add the link as External relationship
        String id = params.getCurrentParagraph()
                .getDocument()
                .getPackagePart()
                .addExternalRelationship(src,
                        XWPFRelation.HYPERLINK.getRelation()).getId();
        // Append the link and bind it to the relationship
        CTHyperlink cLink = params.getCurrentParagraph().getCTP().addNewHyperlink();
        cLink.setId(id);

        // Create the linked text
        CTText ctText = CTText.Factory.newInstance();
        ctText.setStringValue(text);
        CTR ctr = CTR.Factory.newInstance();
        CTRPr rpr = ctr.addNewRPr();

        //设置超链接样式
        CTColor color = CTColor.Factory.newInstance();
        color.setVal("0000FF");
        rpr.setColor(color);
        rpr.addNewU().setVal(STUnderline.SINGLE);

        //设置字体
        CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
        fonts.setAscii("宋体");
        fonts.setEastAsia("宋体");
        fonts.setHAnsi("宋体");

        //设置字体大小
        CTHpsMeasure sz = rpr.isSetSz() ? rpr.getSz() : rpr.addNewSz();
        sz.setVal(new BigInteger("24"));

        ctr.setTArray(new CTText[] { ctText });
        // Insert the linked text into the link
        cLink.setRArray(new CTR[] { ctr });

        // 不再继续渲染a标签下的文字
        params.setContinueItr(false);
        // 追加一个run
        params.createRun();
    }
}
